﻿using CatUtils.Utils.Currency.TextUtils;
using CatUtilsDll.Utils.Currency.WebUtils;
using System;
using System.IO;
using System.Net;
using System.Text;

namespace CatUtils.Utils.SpecialUtils.ContentRecognition.YoudaoUtils.Translate.WebPage
{
    internal class YoudaoTranslatePage
    {
        /// <summary>
        /// 请求主API，需要填写要请求的URL
        /// </summary>
        private string IndexAPI = "http://fanyi.youdao.com/WebpageTranslate?keyfrom=webfanyi.top&url={0}m&type=undefined";

        public static CWebclient YoudaoClient = new CWebclient();

        /// <summary>
        /// 匹配有道
        /// </summary>
        private string RegexYoudao = "http://fanyi.myyoudao.com.*?=webfanyi.top";

        public string Translate(string TranslateUrl)
        {
            YoudaoClient.GetHtml("http://fanyi.youdao.com/");
            ///
            YoudaoClient.GetHtml("http://fanyi.youdao.com/ctlog?pos=&action=MT_BUTTON_CLICK");
            string UserToken = InitAPI(string.Format(IndexAPI, TranslateUrl), YoudaoClient);

            YoudaoClient.Headers.Add("Referer", UserToken);
            YoudaoClient.UploadData(UserToken, new byte[0]);
            return "";
        }

        public WebHeaderCollection InitHeader(string TranslatePostUrl, CWebclient YoudaoClient)
        {
            WebHeaderCollection webHeaderCollection = YoudaoClient.Headers;
            YoudaoClient.Headers.Add("Referer", TranslatePostUrl);
            return webHeaderCollection;
        }

        /// <summary>
        /// 获取初始化API
        /// </summary>
        /// <param name="TranslateUrl"></param>
        /// <returns></returns>
        private string InitAPI(string TranslateUrl, CWebclient YoudaoClient)
        {
            string Shtml = new StreamReader(YoudaoClient.OpenRead(TranslateUrl), Encoding.UTF8).ReadToEnd();

            Console.WriteLine("匹配到" + TextHelper.RegexText(Shtml, RegexYoudao));
            return TextHelper.RegexText(Shtml, RegexYoudao);
        }
    }
}